﻿using Cxuu.Common;
using Cxuu.Models;
using Cxuu.Repository;
using Microsoft.Extensions.DependencyInjection;
using PetaPoco;
using System;
using System.Threading.Tasks;

namespace Cxuu.Service
{
    [UseDI(ServiceLifetime.Scoped)]
    public class NoticeKeyService
    {
        private readonly NoticeKeyRepository _noticeKey;
        private readonly NoticeRepository _notice;
        public NoticeKeyService(NoticeKeyRepository noticeKeyRepository, NoticeRepository noticeRepository)
        {
            _noticeKey = noticeKeyRepository;
            _notice = noticeRepository;
        }

        public virtual async Task InsertAsync(NoticeKey noticeKey)
        {
            await _noticeKey.InsertAsync(noticeKey);
        }

        public async Task<int> DeleteByPriKeyAsync(int id)
        {
            return await _noticeKey.DeleteByPriKeyAsync(id);
        }

        public virtual async Task<Notice> ReadAsync(int id, int noticeId)
        {
            Notice notice = await _notice.GetAsync(noticeId);
            if (notice != null)
            {
                NoticeKey noticeKey = await _noticeKey.GetAsync(id);
                noticeKey.Status = 1;
                noticeKey.ReadTime = DateTime.Now;
                await _noticeKey.UpdateAsync(noticeKey);
                return notice;
            }
            return null;

        }

        public async Task<int> CountAsync(int uid)
        {
            return await _noticeKey.CountAsync(uid);
        }

        public async Task<Page<ViewNotice>> GetPageListAsync(string keyword, int page, int limit, int uid, int? status, int geted)
        {
            return await _noticeKey.GetPageListAsync(keyword, page, limit, uid, status, geted);
        }

        /// <summary>
        /// 批量写入通知 无返回值 
        /// </summary>
        /// <param name="editNotice"></param>
        /// <param name="uid"></param>
        public virtual async Task InsertAsync(EditNotice editNotice, int uid = 0)
        {
            Notice notice = new()
            {
                Title = editNotice.Title,
                PostTime = DateTime.Now,
                PostUid = uid > 0 ? uid : 0,
                Type = uid > 0 ? 1 : 0,
                Content = editNotice.Content,
                Att = editNotice.Att,
            };
            await _notice.InsertAsync(notice);

            string[] uids = editNotice.GetUid.Split(',');
            int[] intUids = Array.ConvertAll(uids, int.Parse);

            for (int i = 0; i < uids.Length; i++)
            {
                NoticeKey noticeKey = new()
                {
                    Nid = notice.Id,
                    GetUid = intUids[i],
                    Status = 0,
                };
                await _noticeKey.InsertAsync(noticeKey);
            }
        }
    }
}
